<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" inline v-show="showSearch" label-width="68px">
      <el-form-item label="投诉标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入投诉标题"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactTel">
        <el-input
          v-model="queryParams.contactTel"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable size="small">
          <el-option
            v-for="dict in complaintStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bid:complaint:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bid:complaint:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bid:complaint:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bid:complaint:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="complaintList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="No." type="index" width="50" />
      <el-table-column label="投诉企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="投诉标题" align="center" prop="title" />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="联系电话" align="center" prop="contactTel" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          {{ getDictValue(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['bid:complaint:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['bid:complaint:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改违规投诉对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="企业名称" prop="enterpriseId">
          <el-input v-model="form.enterpriseName" readonly />
        </el-form-item>
        <el-form-item label="投诉标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入投诉标题" />
        </el-form-item>
        <el-form-item label="投诉信息">
          <editor v-model="form.content" :min-height="192" :height="400" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactTel">
          <el-input v-model="form.contactTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" placeholder="请选择状态">
          <el-select v-model="form.status">
            <el-option
              v-for="dict in complaintStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listComplaint,
  getComplaint,
  delComplaint,
  addComplaint,
  updateComplaint,
  exportComplaint
} from '@/api/bid/complaint';
import Editor from '@/components/MyEditor';

// 响应式状态
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const complaintList = ref([]);
const title = ref("");
const open = ref(false);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  enterpriseId: null,
  title: null,
  content: null,
  contact: null,
  contactTel: null,
  status: null
});

// 表单数据
const form = reactive({
  id: null,
  enterpriseId: null,
  title: null,
  content: null,
  contact: null,
  contactTel: null,
  status: '0',
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
  enterpriseName: null
});

// 投诉状态字典
const complaintStatus = ref([]);

// 表单引用
const queryForm = ref(null);
const formRef = ref(null);

// 工具函数：获取字典数据（请根据实际情况实现）
function getDicts(key) {
  // 示例返回：Promise.resolve({ data: [] })
  return Promise.resolve({ data: [] });
}

function getDictValue(key) {
  const dict = complaintStatus.value.filter(x => x.dictValue === key?.toString());
  return dict && dict.length > 0 ? dict[0].dictLabel : '';
}

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const response = await listComplaint(queryParams);
    complaintList.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: null,
    enterpriseId: null,
    title: null,
    content: null,
    contact: null,
    contactTel: null,
    status: '0',
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    enterpriseName: null
  });
  formRef.value?.resetFields();
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryForm.value?.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加违规投诉';
};

// 修改按钮操作
const handleUpdate = async (row) => {
  reset();
  const id = row?.id || ids.value;
  try {
    const response = await getComplaint(id);
    Object.assign(form, response.data);
    open.value = true;
    title.value = '修改违规投诉';
  } catch (error) {
    console.error(error);
  }
};

// 提交按钮操作
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id != null) {
          await updateComplaint(form);
          ElMessage.success('修改成功');
        } else {
          await addComplaint(form);
          ElMessage.success('新增成功');
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error(error);
      }
    }
  });
};

// 删除按钮操作
const handleDelete = async (row) => {
  const deleteIds = row?.id || ids.value;
  try {
    await ElMessageBox.confirm(
      `是否确认删除违规投诉编号为"${deleteIds}"的数据项?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await delComplaint(deleteIds);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    console.error(error);
  }
};

// 导出按钮操作
const handleExport = async () => {
  try {
    await ElMessageBox.confirm(
      '是否确认导出所有违规投诉数据项?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    const response = await exportComplaint(queryParams);
    // download 为你自定义的下载方法，请根据项目实际情况实现
    download(response.msg);
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getList();
  getDicts('complaint_status').then(x => {
    complaintStatus.value = x.data;
  });
});
</script>
